#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
多语言管理模块
"""

import os
import sys
from typing import Dict, Any


current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)


try:
    from locales.zh_CN import MESSAGES as ZH_CN_MESSAGES
except ImportError:
    ZH_CN_MESSAGES = {}

try:
    from locales.ja_JP import MESSAGES as JA_JP_MESSAGES
except ImportError:
    JA_JP_MESSAGES = {}

try:
    from locales.en_US import MESSAGES as EN_US_MESSAGES
except ImportError:
    EN_US_MESSAGES = {}

# 语言包映射
LANGUAGE_PACKS = {
    'zh-CN': ZH_CN_MESSAGES,
    'ja-JP': JA_JP_MESSAGES,
    'en-US': EN_US_MESSAGES
}

# 多语言配置
DEFAULT_LANGUAGE = 'zh-CN'
SUPPORTED_LANGUAGES = ['zh-CN', 'ja-JP', 'en-US']
FALLBACK_LANGUAGE = 'zh-CN'

# 当前语言
_current_language = DEFAULT_LANGUAGE

def set_language(language: str) -> None:
    """设置当前语言"""
    global _current_language
    if language in SUPPORTED_LANGUAGES:
        _current_language = language
    else:
        _current_language = FALLBACK_LANGUAGE

def get_language() -> str:
    """获取当前语言"""
    return _current_language

def t(key: str, **kwargs) -> str:
    """
    翻译函数
    
    Args:
        key: 消息键
        **kwargs: 格式化参数
    
    Returns:
        翻译后的消息
    """
    messages = LANGUAGE_PACKS.get(_current_language, LANGUAGE_PACKS[DEFAULT_LANGUAGE])
    
    if key not in messages:
        # 如果当前语言没有该键，尝试使用默认语言
        messages = LANGUAGE_PACKS[DEFAULT_LANGUAGE]
        if key not in messages:
            # 如果默认语言也没有，返回键本身
            return key
    
    message = messages[key]
    
    # 格式化消息
    try:
        return message.format(**kwargs)
    except (KeyError, ValueError) as e:
        # 如果格式化失败，返回原始消息
        return message

def get_available_languages() -> list:
    """获取可用语言列表"""
    return list(LANGUAGE_PACKS.keys())

def is_language_supported(language: str) -> bool:
    """检查语言是否支持"""
    return language in LANGUAGE_PACKS
